<!DOCTYPE html>
<html lang="en">
<head>
  <meta name="viewport"
        content="initial-scale=1,maximum-scale=1,user-scalable=no,width=device-width,height=device-height">
  <meta charset="UTF-8">
  <meta name="Author" content="haley">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <script crossorigin="anonymous" integrity="sha384-6ePHh72Rl3hKio4HiJ841psfsRJveeS+aLoaEf3BWfS+gTF0XdAqku2ka8VddikM" src="https://lib.baomitu.com/jquery/1.11.3/jquery.min.js"></script>
  <link crossorigin="anonymous" integrity="sha384-pdapHxIh7EYuwy6K7iE41uXVxGCXY0sAjBzaElYGJUrzwodck3Lx6IE2lA0rFREo" href="https://lib.baomitu.com/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
  <script crossorigin="anonymous" integrity="sha384-pPttEvTHTuUJ9L2kCoMnNqCRcaMPMVMsWVO+RLaaaYDmfSP5//dP6eKRusbPcqhZ" src="https://lib.baomitu.com/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <link href="../imgs/favicon.ico" rel="shortcut icon">
  <script src="../js/goToHome.js"></script>
  <link rel="stylesheet" href="../css/tool/tool.css"/>
  <title>JS工具集代码_haley</title>
  <style>
  </style>
</head>
<body>
<div class="container">
  <h2 class="text-info bg-info pb_10 pt_10 text-center">JS工具集代码_haley</h2>
</div>
<div class="container">
  <h3>/* 字符串操作 */</h3>
  <pre>
    <h4>//中文月日转为英文</h4>
    function returnEnglishMonth(str){
        var data={
            monthEn:["Jan.","Feb.","Mar.","Apr.","May.","June","July","Aug.","Sept","Oct.","Nov.","Dec."],
            dateEn:["st","nd","rd","th"]
        };
        var month=str.split('月')[0];
        var date=str.split('月')[1].split('日')[0];
        if(data&lt;4){
            date=date+data.dateEn[date];
        }else{
            date=date+data.dateEn[3];
        }
        return {
            month:data.monthEn[month],
            date:date
        }
    }
    console.log(returnEnglishMonth('5月4日'));
  </pre>
  <pre>
<h4>// 去掉html标签</h4>
function removeHtmlTab(tab) {
  return tab.replace(/<[^<>]+?>/g,'');//删除所有HTML标签
}
    </pre><pre>
<h4>// 普通字符转换成转意符</h4>
function html2Escape(sHtml) {
  return sHtml.replace(/[<>&"]/g,function(c){return {'<':'&amp;lt;','>':'&amp;gt;','&':'&amp;amp;','"':'&amp;quot;'}[c];});
}
  </pre><pre>
<h4>// 转意符换成普通字符</h4>
function escape2Html(str) {
  var arrEntities={'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'};
  return str.replace(/&(lt|gt|nbsp|amp|quot);/ig,function(all,t){return arrEntities[t];});
}
  </pre><pre>
<h4>// &amp;nbsp;转成空格</h4>
function nbsp2Space(str) {
  var arrEntities = {'nbsp' : ' '};
  return str.replace(/&(nbsp);/ig, function(all, t){return arrEntities[t]})
}
  </pre><pre>
<h4>// 回车转为br标签</h4>
function return2Br(str) {
  return str.replace(/\r?\n/g,"<br />");
}
  </pre><pre>
<h4>// 去除开头结尾换行,并将连续3次以上换行转换成2次换行</h4>
function trimBr(str) {
  str=str.replace(/((\s|&amp;nbsp;)*\r?\n){3,}/g,"\r\n\r\n");//限制最多2次换行
  str=str.replace(/^((\s|&amp;nbsp;)*\r?\n)+/g,'');//清除开头换行
  str=str.replace(/((\s|&amp;nbsp;)*\r?\n)+$/g,'');//清除结尾换行
  return str;
}
  </pre>
  <pre>
<h4>// 将多个连续空格合并成一个空格</h4>
function mergeSpace(str) {
  str=str.replace(/(\s|&amp;nbsp;)+/g,' ');
  return str;
}
</pre>
  <pre>
<h4>// 不能输入中文</h4>
    姓名：<input type="text" class="name" maxlength="10">
$('.name').blur(function(){
		var v=$(this).val();
		console.log(v.search(/[\u4e00-\u9fa5]/));
	  if(v.search(/[\u4e00-\u9fa5]/)!=-1){
	    alert('不能输入中文');
	  }
	});
</pre>
  <pre>
<h4>// 数字转字母，举例1为A，2为B，依次类推</h4>
  function num2Letter(num){
    if(typeof num == 'number' && num&lt;27 && num&gt;0){
      return String.fromCharCode(64 + parseInt(num))
    }else{
      return "输入数据错误,请检查数据。"
    }
  }
</pre>
  <pre>
<h4>// 用来获取url上的参数,获取v的值</h4>
   /* http://demo.chinabrew-beverage.com/videocn/index.htm?v=7  */
    function getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null){
        return unescape(decodeURI(r[2]));
      } else {
        return null;
      }
    }
</pre>
  <pre>
    <h4>// 截取某字符串（含）之前的所有字符串</h4>
     /* */
    var a="/aa/bbbb/cccc/dddd/eee";
    function getUrlString(str,current){
      var arr=str.split('/')
          ,index=arr.indexOf(current);
      if(index!=-1){
        return arr.splice(0,index+1).join('/');
      }else{
        return "path is wrong."
      }
    }
    console.log("点击的路径是 aa：",getUrlString(a,"aa"));
    console.log("点击的路径是 cccc：",getUrlString(a,"cccc"));
    console.log("点击的是非法路径 ccc：",getUrlString(a,"ccc"));
  </pre>
  <code><pre>
    <h4>// js绘制table</h4>
    var data={
      "title":"银行卡支付",
      "content":[
        "中国银行",
        "招商银行",
        "兴业银行",
        "交通银行",
        "上海浦东发展银行",
        "中国建设银行",
        "建行（企业版）",
        "中国民生银行",
        "中国光大银行",
        "中国工商银行",
        "中国农业银行",
        "广东发展银行",
        "中信银行",
        "宁波银行",
        "中国工商银行（企业）",
        "中国农业银行（B2B）",
        "深圳发展银行",
        "杭州银行",
        "上海浦东发展银行（企业版）"
      ]
    },

    function appendHtmlForTable(config){
        var arr=[]
            ,len=config.data.length
            ,cols=config.cols
            ,tdHead=config.tdHead
            ,tdEnd=config.tdEnd;
        arr.push('&lt;tbody>&lt;tr>');
    for(var i=0;i&lt;len;i++){
      if(i%cols!=(cols-1)){
        arr.push(tdHead+config.data[i]+tdEnd);
      }else{
        arr.push(tdHead+config.data[i]+tdEnd);
        arr.push('&lt;/tr>&lt;tr>');
      }
    }
    // 补充不够整行的单元格，避免最后一行缺一块
    for(var j=0;j&lt;cols-i%cols;j++){
      arr.push('&lt;td>&amp;nbsp;&lt;/td>')
    }
    arr.push('&lt;/tr&lt;/tbody>>');
        return arr.join('');
      }
    /* demo示例*/
    var dataTableYinhangka={
        data:null,//初始化的时候传入
        cols:4,//列数
        tdHead:'&lt;td>&lt;label>&lt;input type="radio" name="bank"/>',//头
    tdEnd:'&lt;/label>&lt;/td>',//尾
        init:function(){
          this.data=data.content;
//          console.log(this.data);
        }
      };
      dataTableYinhangka.init();
      $('#payYinhangka').append(appendHtmlForTable(dataTableYinhangka));

  </pre></code>
  <h3>/* 数组操作 */</h3>
    <pre>
        <h4>// 数组累积求和</h4>
        $(function(){
        var arr=[0,1,2,3,4];//[0, 1, 3, 6, 10]
        function arrSum(arr){
            var index=1;
            function changeArr(){
                var tmp=arr[index]+arr[index+1];
                arr.splice(index+1,1,tmp);
                index++;
            }
            for(var i= 0,len=arr.length;i&lt;len;i++){
                changeArr(arr);
            }
            arr.pop();
            arr.pop();
            return arr;
        }
        console.log(arrSum(arr));
    });
    </pre>
    <pre>
        <h4>//判断两个数组是否相同</h4>
    $(function(){
        var arr1=['aaa','222','333','ddd'];
        var arr2=['111','222','333','ddd'];
        function arrCompare(arr1,arr2){
            var arrTmp=[],strTmp='';
            for(var i= 0,len=arr1.length;i&lt;len;i++){
                if(arr1[i]!=arr2[i]){
                    arrTmp.push('0');
                    break;
                }else{
                    arrTmp.push('1');
                }
            }
            strTmp=arrTmp.join('');
//            console.log(strTmp);
            if(strTmp.indexOf('0')!=-1){
                return 0;//不同
            }else{
                return 1;//相同
            }
        }
        if(arrCompare(arr1,arr2)){
            console.log('相同');
        }else{
            console.log('不相同');
        }
    });
    </pre>
  <pre>

<h4>// 判断数组是否含有某个字符串</h4>
function searchStrFromArr(str,arr){
  $.inArray(str, arr);  //3
}
var arr = [ 4, "Pete", 8, "John" ];
searchStrFromArr("John", arr);  //3
searchStrFromArr(4, arr);  //0
searchStrFromArr("David", arr);  //-1
searchStrFromArr("Pete", arr, 2);  //-1
</pre>
  <pre>
<h4>// push改造</h4>
//arr push
  function arrPush(){for(var i= 0,arr=[];i&lt;arguments.length;i++){arr.push(arguments[i]);}return arr;}
  var h=arrPush(
    '&lt;h1>你好&lt;/h1>'
    ,'&lt;div>标题&lt;/div>'
    ,'&lt;span>这里是描述信息&lt;/span>'
  );
  $(function(){
    $('.con').html(h);
  });
  其实push可以直接这样用：
  arr.push(
    '&lt;h1>你好&lt;/h1>'
    ,'&lt;div>标题&lt;/div>'
    ,'&lt;span>这里是描述信息&lt;/span>'
  );
  arr.join('');
</pre>
  <pre>

<h4>//  数组乱序</h4>
function shuffled(arr){
    var res = [];
    for (var i = 0, len = arr.length; i &lt; len; i++) {
      var j = Math.floor(Math.random() * arr.length);
      res[i] = arr[j];
      debugger;
      arr.splice(j, 1);
    }
    return res;
  }
</pre>
  <h3>/* dom */</h3>
  <pre>

<h4>//  动态加载js</h4>
function loadJs(src){
  var oHead = document.getElementsByTagName('HEAD').item(0);
  var oScript= document.createElement("script");
  oScript.type = "text/javascript";
  oScript.src=src;
  oHead.appendChild(oScript);
}
</pre>
  <pre>
<h4>// scroll</h4>
$(window).scroll(function() {
  if($(document).scrollTop()>100){
    /* do some thing */
  }else{
    /* do other some thing */
  }
});
  </pre>
  <pre>
    <h4>滚动获取top值</h4>
    $(window).scroll(function() {
      console.log($(window).scrollTop());
    });
  </pre>
  <pre>
<h4>// 通过宽和宽高比计算高度 </h4>
function getHFromWidth(w,w_h){
  return w/w_h;
}
  </pre>
  <pre>
<h4>// 360浏览器兼容模式判断</h4>
$(function(){
    if (window.navigator.userAgent.indexOf('SLCC2') != -1) {
      alert('360兼容模式')
    }
  });
</pre>
<pre>
<h4>自定义log</h4>
  function log(arg,funName){
    funName =funName||arguments.callee.caller.name;
    console.log(funName+':',arg);
  }
  var a=12343;
  function aa(arg){
    log(arg);
  }
  aa(a);
</pre>
</div>
</body>
</html>
